import { Controller, Post, Headers, HttpException, HttpStatus, RawBodyRequest, Req } from '@nestjs/common'
import { ApiExcludeController } from '@nestjs/swagger'
import * as crypto from 'crypto'
import { Request } from 'express'
@Controller()
@ApiExcludeController() // 隐藏webhook接口
export class WebhookController {
  private config = {
    secret: 'admin888',
  }

  @Post('webhook')
  handleWebhook(
    @Headers('x-gitee-token') signature: string,
    @Req() req: RawBodyRequest<Request>
  ) {
    // 验证请求体是否存在
    if (!req.rawBody) {
      throw new HttpException('请求体为空', 400)
    }

    // 验证 Gitee 签名（防止非法请求）
    if (!this.verifySignature(signature, req.rawBody)) {
      throw new HttpException('签名验证失败', 403)
    }

    try {
      const payload = JSON.parse(req.rawBody.toString())

      // 仅监听 Push 事件（不执行部署，部署由宝塔 WebHook 处理）
      if (payload.action === 'push') {
        console.log('收到 Gitee Push 事件（由宝塔 WebHook 负责部署）')
        console.log('推送信息:', {
          branch: payload.ref,
          commit: payload.commits?.[0]?.message || '无提交信息',
        })
      }

      return {
        code: 0,
        msg: 'WebHook 事件已记录（部署由宝塔 WebHook 处理）',
      }
    } catch (e) {
      console.error('处理 WebHook 失败:', e)
      throw new HttpException('处理 WebHook 失败', 500)
    }
  }

  /**
   * 验证 Gitee 签名
   */
  private verifySignature(signature: string, rawBody: Buffer): boolean {
    if (!signature || !rawBody) {
      return false
    }

    const hmac = crypto.createHmac('sha256', this.config.secret)
    const digest = `sha256=${hmac.update(rawBody).digest('hex')}`

    return signature === digest
  }
}